<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title-box">
        <h3 class="title">养老院管理系统</h3>
        <lang-select />
      </div>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" :placeholder="proxy.$t('login.username')">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          :placeholder="proxy.$t('login.password')"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          :placeholder="proxy.$t('login.code')"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
          <span v-else>{{ proxy.$t('login.logging') }}</span>
        </el-button>
        <div v-if="register" style="float: right">
          <router-link class="link-type" :to="'/register'">{{ proxy.$t('login.switchRegisterPage') }}</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>wxx© 2025</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(true);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', 'true');
      } else {
        // 如果取消勾选，则移除记住的信息
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const rememberMe = localStorage.getItem('rememberMe');
  // 只有在之前勾选了"记住密码"的情况下才加载保存的信息
  if (rememberMe === 'true') {
    const username = localStorage.getItem('username');
    const password = localStorage.getItem('password');
    loginForm.value = {
      username: username === null ? String(loginForm.value.username) : username,
      password: password === null ? String(loginForm.value.password) : String(password),
      rememberMe: true
    } as LoginData;
  } else {
    // 如果没有勾选记住密码，则清空表单
    loginForm.value = {
      username: '',
      password: '',
      rememberMe: false,
      code: '',
      uuid: ''
    } as LoginData;
  }
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login-background-ms.jpg');
  background-size: cover;
  background-position: left center;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(103,178,111,0.1) 100%);
    z-index: 1;
    animation: gradientShift 15s ease infinite;
  }

  .login-form {
    margin-right: 2%;
    border-radius: 20px;
    background: rgba(255, 255, 255, 0.85);
    padding: 45px 50px;
    width: 480px;
    box-shadow: 0 8px 32px rgba(103,178,111, 0.15);
    animation: slideIn 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);
    transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
    position: relative;
    z-index: 2;
    backdrop-filter: blur(8px);

    &:hover {
      transform: translateY(-8px) scale(1.02);
      box-shadow: 0 20px 40px rgba(103,178,111, 0.2);
      background: rgba(255, 255, 255, 0.9);
    }

    .el-input {
      height: 50px;
      margin-bottom: 8px;
      transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);

      input {
        height: 50px;
        border-radius: 12px;
        transition: all 0.3s ease;
        border: 2px solid #e8f5e9;
        font-size: 16px;
        padding-left: 45px;

        &:focus {
          border-color: #67b26f;
          box-shadow: 0 0 15px rgba(103,178,111, 0.2);
          transform: translateY(-2px);
        }
      }
    }

    .input-icon {
      height: 50px;
      width: 18px;
      margin-left: 15px;
      transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
      opacity: 0.7;
      color: #67b26f;
      font-size: 18px;
    }

    .el-input:focus-within {
      transform: translateY(-2px);

      .input-icon {
        transform: scale(1.2) rotate(5deg);
        opacity: 1;
      }
    }

    .el-button {
      height: 50px;
      transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
      background: linear-gradient(45deg, #67b26f, #4ca2cd);
      border: none;
      position: relative;
      overflow: hidden;
      border-radius: 12px;
      font-size: 18px;
      letter-spacing: 2px;

      &:hover {
        transform: translateY(-3px) scale(1.02);
        box-shadow: 0 10px 20px rgba(103,178,111, 0.3);
        background: linear-gradient(45deg, #4ca2cd, #67b26f);
      }
    }
  }
}

.title-box {
  display: flex;
  margin-bottom: 45px;
  position: relative;

  .title {
    margin: 0 auto;
    text-align: center;
    color: #67b26f;
    font-size: 32px;
    font-weight: bold;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    animation: fadeInDown 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);
    letter-spacing: 3px;

    &::after {
      content: '';
      position: absolute;
      bottom: -12px;
      left: 50%;
      width: 80px;
      height: 4px;
      background: linear-gradient(45deg, #67b26f, #4ca2cd);
      transform: translateX(-50%) scaleX(0);
      animation: lineExpand 0.8s cubic-bezier(0.34, 1.56, 0.64, 1) forwards 0.3s;
    }
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 45px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
    transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);

    &:hover {
      transform: scale(1.08) rotate(2deg);
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
  animation: fadeIn 1s ease-out;
  background: linear-gradient(to top, rgba(0,0,0,0.2), transparent);
  backdrop-filter: blur(5px);
  padding: 0 20px;
}

.login-code-img {
  height: 50px;
  padding-left: 12px;
}

@keyframes slideIn {
  0% {
    opacity: 0;
    transform: translateX(50px) scale(0.95);
  }
  60% {
    transform: translateX(-10px) scale(1.02);
  }
  100% {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

@keyframes fadeInDown {
  0% {
    opacity: 0;
    transform: translateY(-30px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes lineExpand {
  from {
    transform: translateX(-50%) scaleX(0);
  }
  to {
    transform: translateX(-50%) scaleX(1);
  }
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.link-type {
  color: #67b26f;
  text-decoration: none;
  transition: all 0.3s ease;
  position: relative;
  font-weight: 500;
  font-size: 15px;

  &::after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 100%;
    height: 2px;
    background: linear-gradient(45deg, #67b26f, #4ca2cd);
    transform: scaleX(0);
    transition: transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  }

  &:hover {
    color: #4ca2cd;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    &::after {
      transform: scaleX(1);
    }
  }
}

.el-checkbox {
  transition: all 0.3s ease;
  color: #666;
  font-size: 15px;

  &:hover {
    color: #67b26f;
  }

  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #67b26f;
    border-color: #67b26f;
  }
}
</style>
